<template>
    <div class="ykd-wrapper" ref="wrap" :class="{'fullscreen':full}">
        <div class="ykd-view" ref="view" v-if="!isPdf&&!isMusic">
            <div class="ykd-view" ref="viewSpin"><span ref="image" class=""></span></div>
        </div>
        <div class="ykd-viewifr" v-if="isPdf">
            <iframe ref="pdfIframe" :src="pdf" frameborder="0" />
        </div>
        <div v-if="isMusic" class="ykd-viewifr" style="margin-top:50%">
          <vedio-form :data="vedioData"></vedio-form>
        </div>
        <div class="ykd-tools">
            <Dropdown class="dropdown" trigger="click">
                <Button type="success" icon="md-menu" title="文件列表" size="small"></Button>
                <DropdownMenu slot="list" style="width:120px;">
                    <Dropdown placement="right-start" v-for="(i,k) in data" :key="k" @on-click="changeItem" style="width:120px;">
                        <DropdownItem>
                            {{i.label}}
                            <Icon type="ios-arrow-forward" />
                        </DropdownItem>
                        <DropdownMenu slot="list" v-for="(item,key) in i.children" :key="key">
                            <DropdownItem :name="k+'-'+key">{{item.label}}</DropdownItem>
                        </DropdownMenu>
                    </Dropdown>
                </DropdownMenu>
            </Dropdown>
            <Button type="primary" icon="md-add" size="small" @click="zoom(1)" title="放大" :disabled="isPdf"></Button>
            <Button type="primary" icon="md-remove" size="small" @click="zoom(-1)" title="缩小" :disabled="isPdf"></Button>
            <Button type="primary" icon="ios-expand" size="small" @click="zoom(0)" title="自适应" :disabled="isPdf"></Button>
            <Button type="primary" icon="ios-skip-backward" size="small" title="上一类" @click="pageType(-1)"></Button>
            <Button type="primary" icon="md-arrow-dropleft" size="small" title="上一张" @click="page(-1)"></Button>
            <Tooltip :content="!full?'点击全屏':'点击关闭全屏'" placement="right-start">
                <Button type="primary" icon="ios-image" size="large" @click="fullscreen"></Button>
            </Tooltip>
            <Button type="primary" icon="md-arrow-dropright" size="small" title="下一张" @click="page(1)"></Button>
            <Button type="primary" icon="ios-skip-forward" size="small" title="下一类" @click="pageType(1)"></Button>
            <Button type="primary" icon="ios-undo" size="small" @click="spin(-1)" title="向左转" :disabled="isPdf"></Button>
            <Button type="primary" icon="ios-redo" size="small" @click="spin(1)"  title="向右转" :disabled="isPdf"></Button>
            <Button type="primary" icon="md-refresh" size="small" @click="spin(0)" title="刷新" :disabled="isPdf"></Button>
            <Button type="primary" icon="md-cloud-download" size="small" @click="downFile()"></Button>
            <Button v-if="fileParam.isShow" type="primary" icon="md-cloud-upload" size="small" @click="showUpload()"></Button>
            <Modal v-model="uploadFile" title="上传附件">
                <Row>
                    <Select placeholder="文件类型" style="width:150px" v-model="AtmtType" @on-change="changeType" label-in-value>
                        <Option v-for="item in attachMents" :value="item.value" :key="item.value">{{item.label}}</Option>
                    </Select>
                    <Upload :on-success="uploadSuccess" :on-error="uploadFail" :on-progress="uploalDealing" :action="UploadUrl()" :show-upload-list="false" name="file" style="margin-left: 160px;margin-top: -32px;">
                        <Button type="primary">上传</Button>
                    </Upload>
                </Row>
            </Modal>
        </div>
        <Spin fix v-show="loading">
            <Icon type="load-c" size=18 class="demo-spin-icon-load"></Icon>
            <div>Loading</div>
        </Spin>
    </div>
</template>

<script>
import vedioForm from './vedio.vue'
export default {
  components: {
    vedioForm
  },
  props: {
    data: Array,
    fileParam: Object,
    attachMents: Array
  },
  data () {
    return {
      scale: 1,
      rotate: 0,
      x: 0,
      y: 0,
      drag: false,
      sPoint: {
        x: 0,
        y: 0
      },
      ox: 50,
      oy: 50,
      full: false,
      parantNode: null,
      currentList: [],
      currentIndex: 0,
      currentTypeIndex: 0,
      isPdf: false,
      pdf: '',
      loading: false,
      uploadFile: false,
      loadingStatus: false,
      atmtTypeName: '',
      AtmtType: '',
      url: this.fileParam.url,
      isMusic: false,
      vedioData: {
        theUrl: null
      },
      file1: 'dist/sample.mp3',
      file2: 'dist/1.mp3'
    }
  },
  watch: {
    scale () {
      this.setAttr()
    },
    rotate () {
      this.setAttr()
    }
  },
  methods: {
    loadImg () {
      console.log(this.currentList[this.currentIndex])
      if (!this.currentList[this.currentIndex]) return
      if (this.currentList[this.currentIndex].fileType === 'V') {
        this.vedioData.theUrl = this.currentList[this.currentIndex].url
        this.isMusic = true
        this.isPdf = false
        return
      } else {
        this.isMusic = false
      }
      if (this.currentList[this.currentIndex].type === 'pdf') {
        this.isPdf = true
        this.isMusic = false
        this.$nextTick(() => {
          this.loading = true
          this.$refs.pdfIframe.onload = () => {
            this.loading = false
          }
          this.$refs.pdfIframe.onerror = () => {
            this.loading = false
            this.$Message.warning('影像图片不存在...')
          }
          this.$refs.pdfIframe.src = this.currentList[this.currentIndex].src
        })
      } else {
        this.isMusic = false
        this.loading = true
        this.isPdf = false
        let img = new Image()
        img.onload = () => {
          this.setImg(img.src)
          this.loading = false
        }
        img.onerror = () => {
          this.loading = false
          this.$Message.warning('影像图片不存在...')
        }
        img.src = this.currentList[this.currentIndex].src
        this.rotate = 0
      }
    },
    setImg (url) {
      this.$refs.image.style.backgroundImage = 'url(' + url + ')'
      this.setInit()
    },
    setAttr () {
      let transformOrigin = []
      transformOrigin.push(this.ox + '%')
      transformOrigin.push(this.oy + '%')
      this.$refs.image.style.transformOrigin = transformOrigin.join(' ')
      console.log('orign:' + transformOrigin.join(' '))
      let transform = []
      transform.push('scale(' + this.scale + ')')
      this.$refs.image.style.transform = transform.join(' ')
      console.log('trans:' + transform.join(' '))
      transform = []
      transform.push('rotate(' + this.rotate + 'deg)')
      this.$refs.viewSpin.style.transform = transform.join(' ')
    },
    zoom (flag) {
      let q = 0.2
      if (flag > 0) {
        this.scale += q
      } else if (flag === 0) {
        this.scale = 1
        this.ox = 50
        this.oy = 50
        let vtransform = []
        vtransform.push('translateX(0px)')
        vtransform.push('translateY(0px)')
        this.$refs.view.style.transform = vtransform.join(' ')
      } else {
        this.scale -= q
        if (this.scale < q) {
          this.scale += q
        }
      }
    },
    spin (flag) {
      let q = 90
      if (flag > 0) {
        this.rotate += q
      } else if (flag === 0) {
        this.rotate = 0
      } else {
        this.rotate -= q
      }
    },
    restore () {
      this.scale = 1
      this.ox = 50
      this.oy = 50
      let vtransform = []
      vtransform.push('translateX(0px)')
      vtransform.push('translateY(0px)')
      this.$refs.view.style.transform = vtransform.join(' ')
      this.rotate = 0
    },
    start (e) {
      console.log('start')
      this.drag = true
      this.sPoint.x = e.pageX
      this.sPoint.y = e.pageY
      // translateX(0px) translateY(0px)
      let transform = this.$refs.view.style.transform
      let x = transform.match(/translateX\(([-0-9]+)px\)/)
      let y = transform.match(/translateY\(([-0-9]+)px\)/)
      this.x = x ? Number(x[1]) : 0
      this.y = y ? Number(y[1]) : 0
    },
    draging (e) {
      e.preventDefault()
      let cPoint = { x: 0, y: 0 }
      if (this.drag) {
        cPoint.x = e.pageX - this.sPoint.x
        cPoint.y = e.pageY - this.sPoint.y
        let transform = []
        transform.push('translateX(' + (this.x + cPoint.x) + 'px)')
        transform.push('translateY(' + (this.y + cPoint.y) + 'px)')
        this.$refs.view.style.transform = transform.join(' ')
      }
    },
    endDrag (e) {
      this.drag = false
    },
    mousewheel (e) {
      e.preventDefault()
      let el = this.$refs.wrap
      this.ox = e.offsetX / el.offsetWidth * 100
      this.oy = e.offsetY / el.offsetHeight * 100
      let delta
      if (e.type === 'DOMMouseScroll' || e.type === 'mousewheel') {
        delta = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3
      }
      if (delta < 0) {
        this.zoom(-1)
      } else {
        this.zoom(1)
      }
    },
    setInit () {
      let el = this.$refs.image
      el.removeEventListener('mousedown', this.start, false)
      el.removeEventListener('mousemove', this.draging, false)
      el.removeEventListener('mouseup', this.endDrag, false)
      el.removeEventListener('mouseout', this.endDrag, false)
      el.removeEventListener('DOMMouseScroll', this.mousewheel, false)
      el.removeEventListener('mousewheel', this.mousewheel, false)

      el.addEventListener('mousedown', this.start, false)
      el.addEventListener('mousemove', this.draging, false)
      el.addEventListener('mouseup', this.endDrag, false)
      el.addEventListener('mouseout', this.endDrag, false)
      el.addEventListener('DOMMouseScroll', this.mousewheel, false)
      el.addEventListener('mousewheel', this.mousewheel, false)
    },
    fullscreen () {
      this.full = !this.full
      if (this.full) {
        document.body.appendChild(this.$el)
        this.$el.style.height = window.innerHeight + 'px'
      } else {
        this.parantNode.appendChild(this.$el)
      }
    },
    changeItem (i) {
      if (i) {
        let ii = i.split('-')
        this.currentTypeIndex = ii[0]
        this.currentList = this.data[ii[0]].children
        this.currentIndex = Number(ii[1])
      }

      this.loadImg()
      this.restore()
    },
    page (flag) {
      if (flag > 0) {
        this.currentIndex += 1
        if (this.currentIndex >= this.currentList.length - 1) {
          this.currentIndex = this.currentList.length - 1
        }
      } else if (flag < 0) {
        this.currentIndex -= 1
        if (this.currentIndex <= 0) {
          this.currentIndex = 0
        }
      }
      this.loadImg()
    },
    pageType (flag) {
      let len = this.data.length
      let yIndex = this.currentTypeIndex
      if (flag > 0) {
        this.currentTypeIndex++
      } else if (flag < 0) {
        this.currentTypeIndex--
      }
      if (this.currentTypeIndex < 0 || this.currentTypeIndex > len - 1) {
        this.currentTypeIndex = yIndex
        return
      }
      let ctIndex = this.currentTypeIndex + '-0'
      this.changeItem(ctIndex)
      this.loadImg()
    },
    uploadSuccess (response) {
      var vm = this
      this.loadingStatus = false
      var code = response.code
      var message = response.message
      if (code !== 'success') {
        this.$Message.warning(message)
        return
      }
      vm.$emit('childInitViewer', null)
      this.uploadFile = false
    },
    uploadFail (error) {
      this.loadingStatus = false
      this.uploadFile = false
      this.$emit('childInitViewer', null)
      this.$Message.warning(error.message)
    },
    uploalDealing () {
      this.loadingStatus = true
    },
    downFile () {
      let fileLocation = this.currentList[this.currentIndex].url
      let params = {}
      let label = this.data[this.currentTypeIndex].children[this.currentIndex].label
      if (label === '') {
        label = this.data[this.currentTypeIndex].label
      }
      let arrs = fileLocation.split('.')
      params.fileName = label + '.' + arrs[arrs.length - 1]
      params.fileLocation = fileLocation
      let aTag = document.createElement('form')
      aTag.setAttribute('action', this.$appContext.marvels_core_approve + 'approve/loanApplication/service/downAttachment')
      aTag.method = 'POST'
      let fileLocationTag = document.createElement('input')
      fileLocationTag.name = 'fileLocation'
      fileLocationTag.value = params.fileLocation
      aTag.appendChild(fileLocationTag)
      let fileNameTag = document.createElement('input')
      fileNameTag.name = 'fileName'
      fileNameTag.value = params.fileName
      aTag.appendChild(fileNameTag)
      document.body.appendChild(aTag)
      aTag.submit()
    },
    showUpload () {
      this.uploadFile = true
    },
    changeType (obj) {
      var posturl = this.url.substring(0, this.url.indexOf('&'))
      this.url = posturl + '&atmtTypeName=' + obj.label + '&AtmtType=' + obj.value
    },
    UploadUrl () {
      return this.url
    }
  },
  created () {
    this.$ajax = this.$util.ajax()
    if (this.data.length > 0) {
      this.currentList = this.data[0].children
    }
  },
  mounted () {
    this.loadImg()
    this.setInit()
    this.parantNode = this.$el.offsetParent
  },
  destroyed () {
    let el = this.$refs.image
    if (el) {
      el.removeEventListener('mousedown', this.start, false)
      el.removeEventListener('mousemove', this.draging, false)
      el.removeEventListener('mouseup', this.endDrag, false)
      el.removeEventListener('mouseout', this.endDrag, false)
      el.removeEventListener('DOMMouseScroll', this.mousewheel, false)
      el.removeEventListener('mousewheel', this.mousewheel, false)
    }
  }
}
</script>

<style lang="less" scoped>
.ykd-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  background: #999;
  overflow: hidden;

  &.fullscreen {
    z-index: 9999;
    position: fixed;
    top: 0;
    left: 0;
  }

  .ykd-tools {
    text-align: center;
    position: absolute;
    width: 100%;
    padding-top: 10px;
  }

  .ykd-view {
    position: absolute;
    width: 100%;
    height: 100%;

    & > span {
      position: absolute;
      width: 100%;
      height: 100%;
      background-repeat: no-repeat;
      background-size: contain;
      background-position: center;
      cursor: move;

      &.effect {
        transition: all 0.4s ease-in;
      }
    }
  }
  .ykd-viewifr {
    position: absolute;
    width: 100%;
    height: 100%;
    & > iframe {
      width: 100%;
      height: 100%;
    }
  }
  .dropdown {
    .ivu-dropdown-menu {
      width: 100px;
      text-align: left;
    }
  }
  .demo-spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
  }
  // .ivu-btn-primary {
  //   color: #fff;
  //   background-color: rgba(0,0,0,.9);
  //   border-color: rgba(0,0,0,.5);
  // }
}
</style>
